﻿@* 
    采购单的退货单 新增/编辑对话框
*@
@using System.Collections.ObjectModel
@using Microsoft.AspNetCore.Components
@inject DialogService DialogService
@inject IProductService ProductService
@inject IBuyOrderService BuyOrderService
@inject IBuyOrderReturnService BuyOrderReturnService
@inject ISupplierService SupplierService

<RadzenStack Gap="1rem">
    <RadzenTemplateForm EditContext="editContext" TItem="BuyOrderReturn" Data="@model" Submit=@OnSubmit>
        <RadzenStack Style="display:flex" class="rz-p-0"
                     Orientation="Orientation.Vertical"
                     AlignItems="AlignItems.Normal"
                     JustifyContent="JustifyContent.SpaceBetween">
            <RadzenCard class="rz-my-6">
                <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Start" Wrap="FlexWrap.Wrap">
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        单据日期
                        <RadzenDatePicker @bind-Value="@model!.CreatedAt" DateFormat="yyyy-MM-dd" />
                    </RadzenStack>
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        客户名称
                        <RadzenDropDown @bind-Value=@model.SupplierId
                                        Data=@Suppliers
                                        Change="OnDropdownChange"
                                        TextProperty="Name"
                                        ValueProperty="Id"
                                        Style="width: 100%;"
                                        Name="DropDownBindValue" />
                    </RadzenStack>
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        订单
                        <RadzenDropDown @bind-Value=@model.BuyOrderId
                                        Data=@BuyOrders
                                        Change="OnDropdownChange"
                                        TextProperty="Name"
                                        ValueProperty="Id"
                                        Style="width: 100%;"
                                        Name="DropDownBindValue" />
                    </RadzenStack>
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        订单编号
                        <RadzenTextBox @bind-Value="@model!.Code" Style="width: 100%" />
                    </RadzenStack>
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        订单标题
                        <RadzenTextBox @bind-Value="@model!.Name" Style="width: 100%" />
                    </RadzenStack>
                    <RadzenStack Orientation="Orientation.Vertical" Gap="4px">
                        备注
                        <RadzenTextBox @bind-Value="@model!.Remark" Style="width: 100%;" />
                    </RadzenStack>
                </RadzenStack>
            </RadzenCard>
            <RadzenStack Orientation="Orientation.Horizontal">
                <RadzenDataGrid Style="flex:1; height:60vh"
                                EmptyText="暂无数据"
                                Data="@model.Details"
                                GridLines="Radzen.DataGridGridLines.Default"
                                AllowPaging="true"
                                AllowSorting="true">
                    <Columns>
                        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                        <RadzenDataGridColumn Property="" Title="操作">
                            <Template Context="data">
                                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                    <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => Delete(data))" ButtonStyle="ButtonStyle.Danger" />
                                </RadzenStack>
                            </Template>
                        </RadzenDataGridColumn>
                        <RadzenDataGridColumn Property="ProductCode" Title="代码" />
                        <RadzenDataGridColumn Property="ProductName" Title="名称" />
                        <RadzenDataGridColumn Property="UnitPrice" Title="名称" />
                        <RadzenDataGridColumn Title="数量">
                            <Template Context="data">
                                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                    <RadzenNumeric @bind-Value="data.Quantity" Min="1" Max="10000" Style="width: 100px;" />
                                </RadzenStack>
                            </Template>
                        </RadzenDataGridColumn>
                        <RadzenDataGridColumn Property="TotalPrice" Title="总价" />
                        <RadzenDataGridColumn Property="Remark" Title="备注" />
                    </Columns>
                </RadzenDataGrid>
                <RadzenDataGrid Style="flex:1; height:60vh"
                                EmptyText="暂无数据"
                                Data="@Products"
                                GridLines="Radzen.DataGridGridLines.Default"
                                AllowPaging="true"
                                AllowSorting="true">
                    <Columns>
                        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                        <RadzenDataGridColumn Property="" Title="操作">
                            <Template Context="data">
                                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                                    <RadzenButton Text="左移" @onclick:stopPropagation Click="@(args => Add(data))" ButtonStyle="ButtonStyle.Danger" />
                                </RadzenStack>
                            </Template>
                        </RadzenDataGridColumn>
                        <RadzenDataGridColumn Property="Name" Title="产品名称" />
                        <RadzenDataGridColumn Property="Unit" Title="产品单位" />
                        <RadzenDataGridColumn Property="Remark" Title="备注" />
                    </Columns>
                </RadzenDataGrid>
            </RadzenStack>
        </RadzenStack>

        <RadzenStack Gap="1rem" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.End" Style="height: 20%;">
            <RadzenButton ButtonStyle="ButtonStyle.Secondary" Text="取消" Click="OnCancel" />
            <RadzenButton ButtonStyle="ButtonStyle.Primary" Text="保存" ButtonType="ButtonType.Submit" />
        </RadzenStack>
    </RadzenTemplateForm>
</RadzenStack>

@code {
    [Parameter]
    public BuyOrderReturn PReturn { get; set; }
    private ObservableCollection<ProductDto> Products { get; set; }
    private IEnumerable<SupplierDto> Suppliers { get; set; }
    private List<BuyOrder> BuyOrders { get; set; }
    private EditContext? editContext;
    private BuyOrderReturn model = default!;

    void OnDropdownChange(object value)
    {
        Console.WriteLine($"Selected Customer: {value}");
        StateHasChanged();
    }

    private async Task Delete(BuyOrderReturnDetail detail)
    {
        try
        {
            model.Details.Remove(detail);
            var product = await ProductService.Get(detail.ProductId);
            if (product == null)
                throw new Exception("产品不存在，无法删除。");
            Products.Add(product);
        }
        catch (Exception e)
        {
           await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    private void Add(ProductDto selectedItem)
    {
        var detail = new BuyOrderReturnDetail
        {
            ProductId = selectedItem.Id,
            Quantity = 1, // 默认数量为1
            UnitPrice = selectedItem.Price,
            Remark = selectedItem.Remark // 可以根据需要设置备注
        };
        model!.Details.Add(detail);
        Products.Remove(selectedItem);
    }

    private void OnCancel()
    {
        DialogService.Close(null);
    }

    void OnSubmit()
    {
        try
        {
            var result = BuyOrderReturnService.Save(model);
            DialogService.Close(result);
        }
        catch (Exception e)
        {
            DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    protected override async void OnInitialized()
    {
        base.OnInitialized();

        if (PReturn.Id == 0)
        {
            model = PReturn;
            editContext = new EditContext(model!);
        }
        else
        {
            model = PReturn;
            editContext = new EditContext(model!);
        }

        // 初始化产品列表
        var products = await ProductService.Search();
        var subSet = products.Where(p => model.Details.All(d => d.ProductId != p.Id)).ToList();
        Products = new ObservableCollection<ProductDto>(subSet);

        // 获取客户列表
        Suppliers = await SupplierService.Search();

        // 如果没有选择客户，则默认选择第一个客户
        if (model.SupplierId == 0)
        {
            model.SupplierId = Suppliers.First().Id;
        }

        // 获取订单列表
        BuyOrders = BuyOrderService.Search(new BaseInput());
        // 如果没有选择订单，则默认选择第一个订单
        if (model.BuyOrderId == 0 && BuyOrders.Count > 0)
        {
            model.BuyOrderId = BuyOrders.First().Id;
        }

    }

}